package com.foreknow.test;

import com.foreknow.bean.Employee;
import com.foreknow.dao.EmployeeMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DyEmployeeMapper {

    public void testSelectEmployeeByIdLike(SqlSession session) {
        EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
        HashMap<String,Object> params = new HashMap();
        //设置id属性
        params.put("id",3);
        List<Employee> list = mapper.selectEmployeeByIdLike(params);
        for (Employee employee:list) {
            System.out.println(employee.getLoginname());
        }
//        list.forEach(employee -> System.out.println(employee));
    }

    public void testSelectEmployeeChoose(SqlSession session) {
        EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
        HashMap<String,Object> params = new HashMap();
//        params.put("id",3);
        params.put("loginname","xxx");
        params.put("password","123456");
        List<Employee> list = mapper.selectEmployeeChoose(params);
        for (Employee employee:list) {
            System.out.println(employee.getLoginname());
        }
    }
    public void testSelectEmployeeIn(SqlSession session){
        EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
        List<Integer> ids = new ArrayList<>();
        ids.add(3);
        ids.add(4);
        List<Employee> list = mapper.selectEmployeeIn(ids);
        System.out.println(list.size());
    }

    public void update(SqlSession session) {
        EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
        Employee employee = mapper.selectEmployeeWithId(4); //根据id查询某个员工
        employee.setLoginname("fender");
        employee.setPassword("111111");
        employee.setName("lio fender");
        mapper.updateEmployeeIfNecessary(employee);
    }
    public static void main(String[] args) throws IOException {
        String resource = "SqlMapConfig.xml";
        //读取并解析配制文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //获取会话工厂SqlSessionFactory
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象，SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
        SqlSession session = sqlSessionFactory.openSession();
        DyEmployeeMapper dyEmployeeMapper = new DyEmployeeMapper();
        //dyEmployeeMapper.testSelectEmployeeByIdLike(session);//调用测试方法
        dyEmployeeMapper.update(session);
        session.commit();
        session.close();
    }
}
